<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="文件名" prop="fileName">
        <el-input
          v-model="queryParams.fileName"
          placeholder="请输入文件名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="关联类型" prop="relationType">
        <el-select v-model="queryParams.relationType" placeholder="请选择关联类型" clearable>
          <el-option label="日记" value="daily" />
          <el-option label="文档" value="document" />
        </el-select>
      </el-form-item>
      <el-form-item label="文件类型" prop="fileType">
        <el-select v-model="queryParams.fileType" placeholder="请选择文件类型" clearable>
          <el-option label="图片" value="image" />
          <el-option label="文档" value="document" />
          <el-option label="视频" value="video" />
          <el-option label="音频" value="audio" />
          <el-option label="其他" value="other" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['note:attachment:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['note:attachment:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['note:attachment:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['note:attachment:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="attachmentList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="文件名" align="center" prop="fileName" :show-overflow-tooltip="true" />
      <el-table-column label="原始名称" align="center" prop="originalName" :show-overflow-tooltip="true" />
      <el-table-column label="文件类型" align="center" prop="fileType">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.fileType == 'image'" type="success">图片</el-tag>
          <el-tag v-else-if="scope.row.fileType == 'document'" type="primary">文档</el-tag>
          <el-tag v-else-if="scope.row.fileType == 'video'" type="warning">视频</el-tag>
          <el-tag v-else-if="scope.row.fileType == 'audio'" type="info">音频</el-tag>
          <el-tag v-else>其他</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="文件大小" align="center" prop="fileSize">
        <template slot-scope="scope">
          {{ formatFileSize(scope.row.fileSize) }}
        </template>
      </el-table-column>
      <el-table-column label="关联类型" align="center" prop="relationType">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.relationType == 'daily'" type="primary">日记</el-tag>
          <el-tag v-else-if="scope.row.relationType == 'document'" type="success">文档</el-tag>
          <el-tag v-else>未知</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="下载次数" align="center" prop="downloadCount" />
      <el-table-column label="上传时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handlePreview(scope.row)"
            v-hasPermi="['note:attachment:query']"
          >预览</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-download"
            @click="handleDownload(scope.row)"
            v-hasPermi="['note:attachment:query']"
          >下载</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['note:attachment:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['note:attachment:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改附件管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="文件上传" prop="file">
          <el-upload
            ref="upload"
            :limit="1"
            accept=".jpg,.jpeg,.png,.gif,.pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.txt,.mp4,.avi,.mp3,.wav"
            :headers="upload.headers"
            :action="upload.url"
            :disabled="upload.isUploading"
            :on-progress="handleFileUploadProgress"
            :on-success="handleFileSuccess"
            :auto-upload="false"
          >
            <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
            <el-button style="margin-left: 10px;" size="small" type="success" :loading="upload.isUploading" @click="submitUpload">上传到服务器</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png/gif/pdf/doc/docx/xls/xlsx/ppt/pptx/txt/mp4/avi/mp3/wav文件，且不超过10MB</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="关联类型" prop="relationType">
          <el-select v-model="form.relationType" placeholder="请选择关联类型">
            <el-option label="日记" value="daily" />
            <el-option label="文档" value="document" />
          </el-select>
        </el-form-item>
        <el-form-item label="关联ID" prop="relationId">
          <el-input v-model="form.relationId" placeholder="请输入关联ID" />
        </el-form-item>
        <el-form-item label="文件描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入文件描述" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 文件预览对话框 -->
    <el-dialog title="文件预览" :visible.sync="previewOpen" width="800px" append-to-body>
      <div v-if="previewFile.fileType === 'image'" style="text-align: center;">
        <img :src="previewFile.filePath" style="max-width: 100%; max-height: 500px;" />
      </div>
      <div v-else-if="previewFile.fileType === 'video'" style="text-align: center;">
        <video :src="previewFile.filePath" controls style="max-width: 100%; max-height: 500px;"></video>
      </div>
      <div v-else-if="previewFile.fileType === 'audio'" style="text-align: center;">
        <audio :src="previewFile.filePath" controls style="width: 100%;"></audio>
      </div>
      <div v-else style="text-align: center; padding: 50px;">
        <i class="el-icon-document" style="font-size: 100px; color: #ccc;"></i>
        <p>该文件类型不支持预览，请下载后查看</p>
      </div>
      <div style="margin-top: 20px;">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="文件名">{{ previewFile.fileName }}</el-descriptions-item>
          <el-descriptions-item label="原始名称">{{ previewFile.originalName }}</el-descriptions-item>
          <el-descriptions-item label="文件类型">{{ previewFile.fileType }}</el-descriptions-item>
          <el-descriptions-item label="文件大小">{{ formatFileSize(previewFile.fileSize) }}</el-descriptions-item>
          <el-descriptions-item label="下载次数">{{ previewFile.downloadCount }}</el-descriptions-item>
          <el-descriptions-item label="上传时间">{{ parseTime(previewFile.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listAttachment, getAttachment, delAttachment, addAttachment, updateAttachment } from "@/api/note/attachment";
import { getToken } from "@/utils/auth";

export default {
  name: "Attachment",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 附件管理表格数据
      attachmentList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示预览对话框
      previewOpen: false,
      // 预览文件信息
      previewFile: {},
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        fileName: null,
        relationType: null,
        fileType: null
      },
      // 表单参数
      form: {},
      // 上传参数
      upload: {
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/common/upload"
      },
      // 表单校验
      rules: {
        relationType: [
          { required: true, message: "关联类型不能为空", trigger: "change" }
        ],
        relationId: [
          { required: true, message: "关联ID不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询附件管理列表 */
    getList() {
      this.loading = true;
      listAttachment(this.queryParams).then(response => {
        this.attachmentList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        attachmentId: null,
        fileName: null,
        originalName: null,
        filePath: null,
        fileSize: null,
        fileType: null,
        relationType: null,
        relationId: null,
        downloadCount: 0,
        description: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.attachmentId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加附件管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const attachmentId = row.attachmentId || this.ids
      getAttachment(attachmentId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改附件管理";
      });
    },
    /** 预览按钮操作 */
    handlePreview(row) {
      this.previewFile = row;
      this.previewOpen = true;
    },
    /** 下载按钮操作 */
    handleDownload(row) {
      // 创建下载链接
      const link = document.createElement('a');
      link.href = row.filePath;
      link.download = row.originalName;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      
      // 增加下载次数
      this.increaseDownloadCount(row.attachmentId);
    },
    /** 增加下载次数 */
    increaseDownloadCount(attachmentId) {
      // 调用后端接口增加下载次数
      // 这里需要在后端添加相应的接口
    },
    /** 文件上传中处理 */
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    /** 文件上传成功处理 */
    handleFileSuccess(response, file, fileList) {
      this.upload.isUploading = false;
      this.form.fileName = response.fileName;
      this.form.originalName = file.name;
      this.form.filePath = response.url;
      this.form.fileSize = file.size;
      this.form.fileType = this.getFileType(file.name);
      this.$modal.msgSuccess(response.msg);
      this.$refs.upload.clearFiles();
    },
    /** 提交上传文件 */
    submitUpload() {
      this.$refs.upload.submit();
    },
    /** 获取文件类型 */
    getFileType(fileName) {
      const ext = fileName.split('.').pop().toLowerCase();
      if (['jpg', 'jpeg', 'png', 'gif', 'bmp'].includes(ext)) {
        return 'image';
      } else if (['mp4', 'avi', 'mov', 'wmv', 'flv'].includes(ext)) {
        return 'video';
      } else if (['mp3', 'wav', 'flac', 'aac'].includes(ext)) {
        return 'audio';
      } else if (['doc', 'docx', 'pdf', 'txt', 'xls', 'xlsx', 'ppt', 'pptx'].includes(ext)) {
        return 'document';
      } else {
        return 'other';
      }
    },
    /** 格式化文件大小 */
    formatFileSize(size) {
      if (size < 1024) {
        return size + ' B';
      } else if (size < 1024 * 1024) {
        return (size / 1024).toFixed(2) + ' KB';
      } else if (size < 1024 * 1024 * 1024) {
        return (size / (1024 * 1024)).toFixed(2) + ' MB';
      } else {
        return (size / (1024 * 1024 * 1024)).toFixed(2) + ' GB';
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.attachmentId != null) {
            updateAttachment(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addAttachment(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const attachmentIds = row.attachmentId || this.ids;
      this.$modal.confirm('是否确认删除附件管理编号为"' + attachmentIds + '"的数据项？').then(function() {
        return delAttachment(attachmentIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('note/attachment/export', {
        ...this.queryParams
      }, `attachment_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>